<script lang="ts" setup>
import {defineEmits, onBeforeUnmount, onMounted, reactive, ref, watch} from "vue";
import {
  Check,
  Close,
  EditPen,
  More, Notification,
  OfficeBuilding,
  Pointer,
  Position,
  Sort,
  Star,
  StarFilled, SuitcaseLine,
  User
} from "@element-plus/icons-vue";
import {getAllTemplateAPI, starTemplateAPI, unstarTemplateAPI, getTemplateByTypeAPI} from "@/api/template";
import {currentUser} from "@/global";
import templateCard from "./TemplateCard.vue"
import {ElMessage} from "element-plus";
import {Editor, EditorContent, useEditor} from '@tiptap/vue-3';
import Text from "@tiptap/extension-text";
import StarterKit from "@tiptap/starter-kit";
import TaskList from "@tiptap/extension-task-list";
import TaskItem from "@tiptap/extension-task-item";
import Table from "@tiptap/extension-table";
import TableRow from "@tiptap/extension-table-row";
import TableHeader from "@tiptap/extension-table-header";
import TableCell from "@tiptap/extension-table-cell";

const emit = defineEmits(['select'])

const innerVisible = ref(false);
const currentTemplateTitle = ref("默认模板");
const currentTemplateContent = ref("默认模板");
const currentTemplateTabTitle = ref("热门")
const dicTemplate = reactive({
  "1":"热门",
  "1-1":"我的收藏",
  "1-2":"我的创建",
  "2":"热门",
  "3":"热门",
  "3-1":"职场办公",
  "3-2":"教育教学",
  "3-3":"写作创作",
});

const editor = new Editor({
  content: ``,
  extensions: [
    StarterKit.configure({
      heading: {
        levels: [1, 2, 3, 4, 5],
      },
    }),
    TaskList,
    TaskItem,
    Text,
    Table,
    TableRow,
    TableHeader,
    TableCell,
  ],
  editable: false
})

// 所有模板
const currentTemplates = ref([])

// 加载时读取模板信息
onMounted(() => {
  getAllTemplateAPI(currentUser.value.id)
      .then((response) => {
        currentTemplates.value = response.data
      })
})

onBeforeUnmount(() => {
  editor.destroy()
})

const toggleStar = (template)=>{
  template.star = !template.star;
  if (template.star) {
    starTemplateAPI(currentUser.value.id, template.id)
        .then((response) => {
          ElMessage.success(response.msg)
        })
  } else {
    unstarTemplateAPI(currentUser.value.id, template.id)
        .then((response) => {
          ElMessage.success(response.msg)
        })
  }
}

const menuCollapsed = ref(false);

const toggleCollapsed = () =>{
  menuCollapsed.value = !menuCollapsed.value;
}

// 选择菜单项目事件处理函数
const handleSelect = (index) =>{
  currentTemplateTabTitle.value = dicTemplate[index];
  if (index.startsWith("3-")) {
    // 获取某分类的模板
    getTemplateByTypeAPI(currentUser.value.id, dicTemplate[index])
        .then((response) => {
          currentTemplates.value = response.data
        })
  } else if (index === '1-1') {
    // 获取我的收藏
    getAllTemplateAPI(currentUser.value.id)
        .then((response) => {
          const list = response.data
          currentTemplates.value = list.filter(item => item.star);
        })
  } else {
    getAllTemplateAPI(currentUser.value.id)
        .then((response) => {
          currentTemplates.value = response.data
        })
  }
}

// 打开模板具体内容
const handleOpenDetail = (templateName, templateContent) => {
  innerVisible.value = true
  currentTemplateTitle.value = templateName
  currentTemplateContent.value = templateContent
  editor.commands.setContent(templateContent)
}

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
</script>

<template>
  <div>
    <!--模板具体内容对话框-->
    <el-dialog
        v-model="innerVisible"
        width="500" height="500" style="border-radius: 10px"
        :title=currentTemplateTitle
        top="25vh"
        append-to-body
    >
      <div class="editor-card">
        <EditorContent :editor="editor"/>
      </div>
      <template #footer>
        <div style="margin-top: 0">
          <el-button @click="innerVisible = false">
            <el-icon style="vertical-align: middle" :size="16">
              <Close />
            </el-icon>
            <span style="vertical-align: middle"> 取消 </span>
          </el-button>
          <el-button type="primary" @click="innerVisible = false; emit('select', currentTemplateContent)">
            <el-icon style="vertical-align: middle" :size="16">
              <Check />
            </el-icon>
            <span style="vertical-align: middle"> 确定 </span>
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-container style="height: 500px">
      <el-aside :width="'150'">
        <el-scrollbar>
          <el-menu :default-openeds="['1', '3']" @select="handleSelect" :collapse="menuCollapsed" default-active="2" @open="handleOpen" @close="handleClose">
            <el-sub-menu index="1">
              <template #title>
                <el-icon><User /></el-icon>
                <span>我的</span>
              </template>
              <el-menu-item index="1-1">
                <template #title>
                  <el-icon><Star /></el-icon>
                  <span>我的收藏</span>
                </template>
              </el-menu-item>
              <el-menu-item index="1-2">
                <template #title>
                  <el-icon><Pointer /></el-icon>我的创建
                </template>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item index="2">
              <el-icon><Notification /></el-icon>
              <template #title>
                <span>热门</span>
              </template>
            </el-menu-item>
            <el-sub-menu index="3">
              <template #title>
                <el-icon><More /></el-icon>
                <span>分类</span>
              </template>
              <el-menu-item index="3-1">
                <template #title>
                  <el-icon><OfficeBuilding /></el-icon>职场办公
                </template>
              </el-menu-item>
              <el-menu-item index="3-2">
                <template #title>
                  <el-icon><SuitcaseLine /></el-icon>教育教学
                </template>
              </el-menu-item>
              <el-menu-item index="3-3">
                <template #title>
                  <el-icon><EditPen /></el-icon>写作创作
                </template>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-scrollbar>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px" height="20px">
          <el-tooltip
              class="box-item"
              effect="dark"
              content="展开/折叠菜单"
              placement="top"
          >
            <el-button circle @click="toggleCollapsed" :icon="Sort" style="margin-right: 15px"/>
          </el-tooltip>
          <span style="font-size: 15px;color: #1b1b1b">{{ currentTemplateTabTitle }}</span>
        </el-header>

        <el-main>
          <el-scrollbar>
            <el-space wrap>
              <template-card
                  v-for="(template , idx) in currentTemplates"
                  :key="idx"
                  :m-title = "template.name"
                  :m-description = "template.description"
                  :is-star = "template.star"
                  @toggle-star="toggleStar(template)"
                  @start-template="handleOpenDetail(template.name, template.content);"
              />
            </el-space>
          </el-scrollbar>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>

.tiptap {
  > * + * {
    margin-top: 0.75em;
  }

  ul {
    padding: 0 2rem;
    list-style: square;
  }
  ol {
    padding: 0 2rem;
    list-style: decimal;
  }
  table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 100%;
    margin: 0;
    overflow: hidden;

    td,
    th {
      min-width: 1em;
      border: 2px solid #ced4da;
      padding: 3px 5px;
      vertical-align: top;
      box-sizing: border-box;
      position: relative;

      > * {
        margin-bottom: 0;
      }
    }

    th {
      font-weight: bold;
      text-align: left;
      background-color: #f1f3f5;
    }

    .selectedCell:after {
      z-index: 2;
      position: absolute;
      content: '';
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background: rgba(200, 200, 255, 0.4);
      pointer-events: none;
    }

    .column-resize-handle {
      position: absolute;
      right: -2px;
      top: 0;
      bottom: -2px;
      width: 4px;
      background-color: #adf;
      pointer-events: none;
    }

    p {
      margin: 0;
    }
  }
  pre {
    background: #0d0d0d;
    color: #fff;
    font-family: 'JetBrainsMono', monospace;
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;

    code {
      color: inherit;
      padding: 0;
      background: none;
      font-size: 0.8rem;
    }

    .hljs-comment,
    .hljs-quote {
      color: #616161;
    }

    .hljs-variable,
    .hljs-template-variable,
    .hljs-attribute,
    .hljs-tag,
    .hljs-name,
    .hljs-regexp,
    .hljs-link,
    .hljs-name,
    .hljs-selector-id,
    .hljs-selector-class {
      color: #f98181;
    }
    .hljs-number,
    .hljs-meta,
    .hljs-built_in,
    .hljs-builtin-name,
    .hljs-literal,
    .hljs-type,
    .hljs-params {
      color: #fbbc88;
    }

    .hljs-string,
    .hljs-symbol,
    .hljs-bullet {
      color: #b9f18d;
    }

    .hljs-title,
    .hljs-section {
      color: #faf594;
    }

    .hljs-keyword,
    .hljs-selector-tag {
      color: #70cff8;
    }

    .hljs-emphasis {
      font-style: italic;
    }

    .hljs-strong {
      font-weight: 700;
    }
  }
}

.editor-card {
  height: 200px;
  overflow-y: scroll;
  border-radius: 10px;
  border: 1px solid #e9e9e9;
  padding: 0 10px 5px 15px;
  box-shadow: 5px 5px 8px rgba(0, 0, 0, 0.04);
  margin-top: 0;
}

</style>